import { CommonModule } from '@angular/common';
import { ChangeDetectorRef, Component, DestroyRef, inject, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormsModule } from '@angular/forms';
import { finalize } from 'rxjs';

import { JsonPatchData } from '@app/core/domain/json-patch-data';
import { RequestParams } from '@app/core/domain/request-params';
import { CardRegex, CardRegexService } from '@app/core/services/http/card-regex/card-regex.service';
import { ScanRecord } from '@app/core/services/http/scan-record/scan-record.service';
import { PageSearchParams } from '@app/pages/system-manage/dept/dept.component';
import { AntTableComponent, AntTableConfig, SortFile } from '@app/shared/components/ant-table/ant-table.component';
import { CardTableWrapComponent } from '@app/shared/components/card-table-wrap/card-table-wrap.component';
import { PageHeaderComponent, PageHeaderType } from '@app/shared/components/page-header/page-header.component';
import { WaterMarkComponent } from '@app/shared/components/water-mark/water-mark.component';
import { ModalBtnStatus } from '@app/widget/base-modal';
import { NzBadgeModule } from 'ng-zorro-antd/badge';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzCardModule } from 'ng-zorro-antd/card';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzFormModule } from 'ng-zorro-antd/form';
import { NzGridModule } from 'ng-zorro-antd/grid';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzMessageModule, NzMessageService } from 'ng-zorro-antd/message';
import { NzPopconfirmModule } from 'ng-zorro-antd/popconfirm';
import { NzSpaceModule } from 'ng-zorro-antd/space';
import { NzTableQueryParams } from 'ng-zorro-antd/table';

import { CardRegexModalService } from './card-regex-modal/card-regex-modal.service';
import { ValidationModalService } from './validation-modal/validation-modal.service';

@Component({
  selector: 'app-login-log',
  standalone: true,
  imports: [
    NzMessageModule,
    PageHeaderComponent,
    FormsModule,
    NzFormModule,
    NzGridModule,
    NzInputModule,
    NzButtonModule,
    NzIconModule,
    CardTableWrapComponent,
    AntTableComponent,
    CommonModule,
    NzPopconfirmModule,
    NzBadgeModule,
    NzSpaceModule,
    NzCardModule,
    WaterMarkComponent
  ],
  templateUrl: './card-regex.component.html',
  styleUrl: './card-regex.component.less'
})
export class CardRegexComponent implements OnInit {
  @ViewChild('operationTpl', { static: true }) operationTpl!: TemplateRef<NzSafeAny>;
  pageSearchParam: Partial<PageSearchParams> = {};
  tableConfig!: AntTableConfig;
  pageHeaderInfo: Partial<PageHeaderType> = {
    title: '匹配规则',
    breadcrumb: ['首页', '功能菜单', '匹配规则']
  };
  isCollapse: boolean = true;

  cardRegexes: CardRegex[] = [];
  checkedCashArray: NzSafeAny[] = [];
  private readonly destroyRef = inject(DestroyRef);
  private readonly messageService: NzMessageService = inject(NzMessageService);
  private readonly cardRegexService: CardRegexService = inject(CardRegexService);
  private readonly validationModalService: ValidationModalService = inject(ValidationModalService);
  private readonly cardRegexModalService: CardRegexModalService = inject(CardRegexModalService);
  private readonly cdr: ChangeDetectorRef = inject(ChangeDetectorRef);

  private initTable(): void {
    this.tableConfig = {
      headers: [
        {
          title: '规则',
          width: 130,
          field: 'regexexpression',
          show: true,
          showSort: false
        },
        {
          title: '操作',
          tdTemplate: this.operationTpl,
          width: 120,
          fixed: true,
          fixedDir: 'right'
        }
      ],
      total: 0,
      showCheckbox: false,
      loading: false,
      pageSize: 10,
      pageIndex: 1
    };
  }

  selectedChecked(e: NzSafeAny): void {
    this.checkedCashArray = [...e];
  }

  resetForm(): void {
    this.pageSearchParam = {};
    this.search();
  }

  toggleCollapse(): void {
    this.isCollapse = !this.isCollapse;
  }

  reloadTable(): void {
    this.messageService.info('已经刷新了');
    this.getCardRegexes();
  }

  tableChangeDetection(): void {
    this.cardRegexes = [...this.cardRegexes];
    this.cdr.detectChanges();
  }

  tableLoading(isLoading: boolean): void {
    this.tableConfig.loading = isLoading;
    this.tableChangeDetection();
  }

  appendRequestParams(): RequestParams {
    const filter: Partial<ScanRecord> = {};
    let requestParams: RequestParams = {
      '@relationships': 'UserInfo',
      current: this.tableConfig.pageIndex,
      pageSize: this.tableConfig.pageSize,
      '@filter': '',
      ...filter
    };

    if (this.pageSearchParam.Name) {
      requestParams['@filter'] += `contains(RegexExpression,${this.pageSearchParam.Name})`;
    }

    return requestParams;
  }

  getCardRegexes(e?: NzTableQueryParams): void {
    if (e) {
      this.tableConfig.pageIndex = e?.pageIndex;
    }
    this.checkedCashArray = [...this.checkedCashArray];
    this.tableLoading(true);
    const requestParams: RequestParams = this.appendRequestParams();

    this.cardRegexService
      .getEntityPageList(requestParams)
      .pipe(
        finalize(() => this.tableLoading(false)),
        takeUntilDestroyed(this.destroyRef)
      )
      .subscribe(cardRegex => {
        const { records, total } = cardRegex;
        this.cardRegexes = records;
        this.tableConfig.total = total;
      });
  }

  changeSort(e: SortFile): void {
    //e.fileName , e.sortDir
  }

  changePageSize(e: number): void {
    this.tableConfig.pageSize = e;
  }

  search(): void {
    this.tableConfig.pageIndex = 1;
    this.getCardRegexes();
  }

  add(): void {
    this.cardRegexModalService
      .show({ nzTitle: '新增' })
      .pipe(
        finalize(() => this.tableLoading(false)),
        takeUntilDestroyed(this.destroyRef)
      )
      .subscribe(res => {
        if (!res || res.status === ModalBtnStatus.Cancel) {
          return;
        }
        const param = { ...res.modalValue };
        this.tableLoading(true);
        this.addEditData(param, 'addEntity');
      });
  }

  edit(id: number): void {
    this.cardRegexService
      .getEntityById(id)
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(res => {
        this.cardRegexModalService
          .show({ nzTitle: '编辑' }, res[0])
          .pipe(
            finalize(() => this.tableLoading(false)),
            takeUntilDestroyed(this.destroyRef)
          )
          .subscribe(({ modalValue, status }) => {
            if (status === ModalBtnStatus.Cancel) {
              return;
            }
            modalValue.id = id;
            this.tableLoading(true);
            this.addEditData(modalValue, 'editEntity');
          });
      });
  }

  openValidationModal(id: number): void {
    this.cardRegexService
      .getEntityById(id)
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe((result: CardRegex[]) => {
        this.validationModalService
          .show({ nzTitle: '校验规则' }, result[0])
          .pipe(
            finalize(() => this.tableLoading(false)),
            takeUntilDestroyed(this.destroyRef)
          )
          .subscribe(res => {
            if (!res || res.status === ModalBtnStatus.Cancel) {
              return;
            }
          });
      });
  }

  addEditData(param: CardRegex, methodName: 'editEntity' | 'addEntity'): void {
    this.cardRegexService[methodName]([param])
      .pipe(
        finalize(() => this.tableLoading(false)),
        takeUntilDestroyed(this.destroyRef)
      )
      .subscribe(() => this.getCardRegexes());
  }

  del(id: number): void {
    this.cardRegexService.delEntities([id]).subscribe(() => {
      if (this.cardRegexes.length === 1) {
        this.tableConfig.pageIndex = this.tableConfig.pageIndex - 1;
      }
      this.getCardRegexes();
    });
  }

  ngOnInit(): void {
    this.initTable();
  }
}
